package shan.rpc.yurpc.proxy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.databind.ser.Serializers;
import shan.rpc.yurpc.RpcApplication;
import shan.rpc.yurpc.config.RpcConfig;
import shan.rpc.yurpc.constant.RpcConstant;
import shan.rpc.yurpc.model.RpcRequest;
import shan.rpc.yurpc.model.RpcResponse;
import shan.rpc.yurpc.model.ServiceMetaInfo;
import shan.rpc.yurpc.registry.Registry;
import shan.rpc.yurpc.registry.RegistryFatory;
import shan.rpc.yurpc.serializer.JdkSerializer;
import shan.rpc.yurpc.serializer.Serializer;
import shan.rpc.yurpc.serializer.SerializerFactory;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 服务代理（JDK动态代理）
 */
public class ServiceProxy implements InvocationHandler {
    /**
     * 调用代理
     */
    @Override
    public Object invoke(Object proxy, Method method,Object[] args) throws Throwable{
        //指定序列化器
        final Serializer serializer= SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

        //构造请求
        String servicName=method.getDeclaringClass().getName();
        RpcRequest rpcRequest=RpcRequest.builder()
                .serviceName(servicName)
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        try{
            //序列化
            byte[] bodyBytes=serializer.serialize(rpcRequest);
            //从注册中心获取服务提供者请求地址
            RpcConfig rpcConfig=RpcApplication.getRpcConfig();
            Registry registry= RegistryFatory.getInstance(rpcConfig.getRegistryConfig().getRegistry());
            ServiceMetaInfo serviceMetaInfo=new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(servicName);
            serviceMetaInfo.setServiceVersion(RpcConstant.DEFAULT_SERVICE_VERSION);
            List<ServiceMetaInfo> serviceMetaInfoList=registry.serviceDiscovery(serviceMetaInfo.getServiceKey());
            if(CollUtil.isEmpty(serviceMetaInfoList)){
                throw new RuntimeException("暂无服务地址");
            }
            //暂时先取第一个
            ServiceMetaInfo selectedServiceMetaInfo=serviceMetaInfoList.get(0);
            //发生请求
            //todo 这里的地址被硬编码了
            try(HttpResponse httpResponse=
                        HttpRequest.post(selectedServiceMetaInfo.getServiceAddress())
                                .body(bodyBytes)
                                .execute()){
                byte[] result=httpResponse.bodyBytes();
                RpcResponse rpcResponse=serializer.deserialize(result,RpcResponse.class);
                return rpcResponse.getData();
            }
        }catch (IOException e){
            System.out.println(e);
            e.printStackTrace();
        }
        return null;
    }
}
